import { ValidatorFn, AbstractControl } from '@angular/forms'

interface PhoneOptions {
  /**
   * 万能字符 用于绕过校验
   */
  universalCharacter?: string

  /**
   * 校验模式 default = 'both'
   */
  mode?: 'both' | 'phone' | 'mobile'
}

/**
 * 手机号码验证
 */
export function phone(options: PhoneOptions = {}): ValidatorFn {
  const { universalCharacter, mode = 'both' } = options
  return (control: AbstractControl): { [key: string]: any } | null => {
    const number = control.value
    if (number === universalCharacter || (!number && number !== 0)) {
      return null
    }
    const isMobile = /^(1[3-9][0-9])\d{8}$/.test(number)
    const isPhone = /0\d{2,3}-\d{7,8}/.test(number)
    if (mode === 'mobile' && isMobile === false) {
      return { 格式不正确: false }
    } else if (mode === 'phone' && isPhone === false) {
      return { 格式不正确: false }
    } else if (mode === 'both' && isMobile === false && isPhone === false) {
      return { 格式不正确: false }
    }
    return null
  }
}
